package com.hll.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

// 发送简单的文字信息, 亲测有效, 使用前请更换mail and code
public class SendTextMail {
  private static String mail = "2621365348@qq.com";
  private static String code = "hztnbbtkaoyfecic"; // qq邮箱网页端-设置-账户-开启pop3

  public static void main(String[] args) {
    try {
      sendMail(mail, code, mail, "hello mail", "<h1 style='color:red;'>haha</h1>");
    } catch (MessagingException | GeneralSecurityException e) {
      e.printStackTrace();
    }
  }

  // form->to, code授权码, subject主题,content文本内容
  public static void sendMail(String from, String code, String to, String subject, String content)
      throws MessagingException, GeneralSecurityException {
    // 创建一个配置文件并保存
    Properties properties = new Properties();

    properties.setProperty("mail.host", "smtp.qq.com");

    properties.setProperty("mail.transport.protocol", "smtp");

    properties.setProperty("mail.smtp.auth", "true");

    // QQ存在一个特性设置SSL加密
    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    properties.put("mail.smtp.ssl.enable", "true");
    properties.put("mail.smtp.ssl.socketFactory", sf);

    // 创建一个session对象
    Session session =
        Session.getDefaultInstance(
            properties,
            new Authenticator() {
              @Override
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mail, code);
              }
            });

    // 开启debug模式,不开没有任何提示信息
    session.setDebug(true);

    // 获取连接对象
    Transport transport = session.getTransport();

    // 连接服务器
    transport.connect("smtp.qq.com", mail, code);

    // 创建邮件对象
    MimeMessage mimeMessage = new MimeMessage(session);

    // 邮件发送人
    mimeMessage.setFrom(new InternetAddress(mail));

    // 邮件接收人
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 自己给自己发送

    // 邮件标题
    mimeMessage.setSubject(subject);

    // 邮件内容,其实可以放html代码，接收方可以显示,其实邮件内容本质就是html
    mimeMessage.setContent(content, "text/html;charset=UTF-8");

    // 发送邮件
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

    // 关闭连接
    transport.close();
  }
}
